<template>
  <div class="bodyBar">
    <div class="tableBar">
      <el-input
          placeholder="请输入姓名进行搜索"
          v-model="searchName"
          @input="handleSearch"
          style="width: 250px; margin-right: 20px;"
      ></el-input>
      <el-button icon="el-icon-search" circle></el-button>
    </div>
    <div class="button-container">
      <el-button @click="upload_dialog.open=true">上传</el-button>
      <el-button>删除</el-button>
    </div>
    <el-table  :data="tableData" style="width: 100%" class="custom-table">
      <el-table-column
          label="选择"
          width="55"
      >
        <template slot-scope="scope">
          <label class="custom-checkbox">
            <input
                type="checkbox"
                v-model="scope.row.isSelected"
                @change="handleCheckboxChange(scope.$index, scope.row)"
            >
            <div class="checkmark"></div>
          </label>
        </template>
      </el-table-column>
      <el-table-column prop="nickName" label="文件名" width="180"></el-table-column>
      <el-table-column label="封面">
        <template slot-scope="scope">
          <img :src="scope.row.base64" alt="Article Cover" style="width: 100px; height: 100px;">
        </template>
      </el-table-column>
      <el-table-column
          label="下载链接">
        <template slot-scope="scope">
          <a
              :href="`/api/${scope.row.bucketName}/${scope.row.fileName}.${scope.row.extension}`"
              :download="`${scope.row.fileName}.${scope.row.extension}`">
            {{ `${scope.row.fileName}` }} </a>
        </template>
      </el-table-column>
      <el-table-column prop="uploadTime" label="上传时间" width="180"></el-table-column>
      <el-table-column prop="extension" label="文件类型" width="120"></el-table-column>
      <el-table-column label="文件大小" width="120">
        <template slot-scope="scope">
          <span>{{ formatFileSize(scope.row.fileSize) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
<!--          <el-button @click="handleView(scope.row)">播放</el-button>
          <el-button type="danger" @click="handleDelete(scope.row)">删除</el-button>-->
          <el-button type="primary" icon="el-icon-video-play" @click="handleView(scope.row)"></el-button>
          <el-button type="primary" icon="el-icon-delete" @click="handleDelete(scope.row)"></el-button>
<!--          <el-button type="primary" icon="el-icon-download" @click="downloadFile(scope.row.bucketName,scope.row.fileName)"></el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="upload_dialog.open" :title="'文件上传'" width="30%" >
      <el-form inline class="horizontal-form">
        <el-form-item label="存储桶名：" prop="bucketName">
          <el-input v-model="upload_dialog.bucketName" placeholder="请输入存储桶名"></el-input>
        </el-form-item>
        <el-form-item label="文件名：" prop="nickName">
          <el-input v-model="upload_dialog.nickName" placeholder="请输入文件名"></el-input>
        </el-form-item>
      </el-form>
      <div class="upload-container">
        <el-upload
            class="upload-demo"
            action="#"
            :multiple="false"
            :on-change="hanleFileSelected"
            :file-list="upload_dialog.fileList"
            :auto-upload="false"
            :accept="accept">
          <el-button size="small" type="primary">文件上传</el-button>
        </el-upload>
        <el-upload
            class="upload-demo"
            action="#"
            :multiple="false"
            :on-change="imageSelected"
            :auto-upload="false"
            accept="image/*">
          <el-button size="small" type="primary">封面上传</el-button>
        </el-upload>
      </div>
<!--      <el-upload
          class="upload-demo"
          action="#"
          drag
          :multiple="false"
          :on-change="hanleFileSelected"
          :file-list="upload_dialog.fileList"
          :auto-upload="false"
          :accept="accept"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        &lt;!&ndash;        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>&ndash;&gt;
      </el-upload>-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="upload_dialog.open=false">取消</el-button>
          <el-button @click="upload">确认</el-button>
        </span>
    </el-dialog>
    <div class="loader-background" v-if="loader"></div>
    <div class="loader" v-if="loader"></div>
  </div>
</template>

<script>
import SparkMd5 from 'spark-md5'
import $axios from 'axios';
export default {
  data() {
    return {
      accept: 'video/*',
      loader: false,
      fileList: [],
      upload_dialog: {
        open: false,
        bucketName: '',
        nickName: '',
        fileList:[],
        file: null,
        base64: ''
      },
      showPdfDialog: false,
      pdfSrc: '', // 这里替换为你的PDF文件路径或URL
      currentPage: 1,
      totalPages: 0,
      value1: '',
      tableData: [],
      dialogImageUrl: '',
      dialogVisible: false
    };
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      await this.getFiles("video").then(res =>{
        if (String(res.data.code) === '200') {
          this.tableData = res.data.data
          console.log(this.tableData)
        }
      })
    },
    imageSelected(file) {
      const reader = new FileReader();
      reader.addEventListener('load', (event) => {
        this.upload_dialog.base64 = event.target.result; // 获取图片的 base64 编码
        console.log(this.upload_dialog.base64)
      });
      reader.readAsDataURL(file.raw); // 读取文件并将其转为 base64

    },
    upload(){
      let file = this.upload_dialog.file
      let metaFile
      this.loader = true;
      this.$axios.post('/api/meta',{
        fileSize: file.size,
        extension: file.name.substr(file.name.lastIndexOf('.') ? file.name.lastIndexOf('.') : 0 ),
        bucketName: this.upload_dialog.bucketName,
        nickName: this.upload_dialog.nickName,
        fileType: "video",
        base64: this.upload_dialog.base64
      }).then(res => {
        console.log(res.data)
        metaFile = res.data.data
      }).then(res =>{
        let chunks = metaFile.chunks
        let filename = metaFile.filename
        let bucketName = metaFile.bucketName
        let taskCount = 0
        for (let chunk of chunks){
          if (chunk.completed){
            continue
          }
          let chunkContent = file.slice(chunk.chunkStart,chunk.chunkStart + chunk.chunkSize)
          console.log(chunkContent)
          const formData = new FormData()
          formData.append('chunkNo',chunk.chunkNo)
          formData.append('file',chunkContent)
          formData.append('bucketName',bucketName)
          formData.append('filename',filename)
          new Promise((res,rej) => {
            let fileReader = new FileReader()
            let spark = new SparkMd5.ArrayBuffer()
            fileReader.readAsArrayBuffer(chunkContent)
            fileReader.onload = (e) => {
              spark.append(e.target.result)
              let md5 = spark.end()
              res(md5)
            }
          }).then(md5 => {
            formData.append('md5',md5)
            this.$axios.post('/api/chunk/upload',formData)
                .then(res => {
                  console.log(res)
                  chunk.completed = true
                  taskCount += 1
                  if (taskCount == chunks.length){
                    this.init()
                    this.$message('文件上传完成')
                    this.loader = false
                    this.upload_dialog ={
                      open: false,
                      bucketName: '',
                      nickName: '',
                      fileList:[],
                      file: null
                    }
                  }
                })
          })
        }
      })
    },
    handleView(row) {
      this.$router.push({ name: 'player', params: {
        bucketName: row.bucketName,
        extension: row.extension,
        filename: row.fileName} })
    },
    handleEdit(row) {
      // 编辑文章逻辑
      console.log('编辑文章:', row);
    },
    handleDelete(row) {
      // 删除文章逻辑
      console.log('删除文章:', row);
    },
    hanleFileSelected(file,fileList){
      this.upload_dialog.file = file.raw
    },
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];

      // 如果你想要特定的逻辑来只在超过1GB时显示G，可以这样修改：
      if (bytes >= 1024 * 1024 * 1024) { // 1GB
        return (bytes / (1024 * 1024 * 1024)).toFixed(2) + ' G';
      } else if (bytes >= 1024 * 1024) { // 1MB
        return (bytes / (1024 * 1024)).toFixed(2) + ' MB';
      } else {
        // 你可以添加更多逻辑来处理KB以下的情况
        return (bytes / 1024).toFixed(2) + ' KB';
      }
    },
    getFiles(fileType) {
      return $axios({
        url: '/info/meta/files/' + fileType,
        method: 'get',
      })
    },
    async downloadFile(bucketName, fileName) {
      try {
        // 发送 GET 请求到你的下载接口
        const response = await $axios({
          method: 'get',
          url: '/api/' + bucketName + '/' + fileName, // 替换为你的实际接口路径
          responseType: 'blob', // 指示axios期望服务器返回的数据类型为blob
        });

        // 创建Blob对象
        const blob = new Blob([response.data], { type: response.headers['content-type'] });

        // 创建一个a标签用于下载
        const link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        // 设置文件名
        link.setAttribute('download', fileName + (response.headers['content-disposition'] && response.headers['content-disposition'].includes('filename=') ?
            response.headers['content-disposition'].split('filename=')[1].replace(/["']/g, '') :
            '')); // 尝试从Content-Disposition头中获取文件名

        // 触发下载
        document.body.appendChild(link);
        link.click();

        // 然后移除a标签
        document.body.removeChild(link);

      } catch (error) {
        console.error('Failed to download file:', error);
        // 根据需要处理错误，比如显示错误消息给用户
      }
    }
  }
}
</script>

<style>
.loader-background {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  z-index: 9999; /* 确保它位于其他元素之上 */
}
.upload-container {
  display: flex;
  justify-content: center;
  margin-bottom: 15px;
}
.upload-demo{
  padding: 10px;
}
.bodyBar{
  padding: 20px;
  background: #FFFFFF;
}
.horizontal-form .el-form-item__label {
  float: left; /* 标题浮动到左边 */
  text-align: right; /* 可以根据需要调整标题的对齐方式 */
  width: 100px; /* 根据需要设置标题的宽度 */
  line-height: 32px; /* 根据输入框的高度设置行高，以保持垂直对齐 */
}

.horizontal-form .el-form-item__content {
  /*margin-left: 100px;*/ /* 根据标题的宽度和间距设置内容区域的左边距 */
}

/* 如果需要调整输入框的宽度，可以单独设置 */
.horizontal-form .el-input__inner {
  width: 200px; /* 设置为你想要的宽度 */
}
.el-button--primary {
  background-color: #6871f1;
  border-color: #6871f1;
}
.input-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 10px; /* 使用gap来添加上下间隔 */
}

.input-container .el-input {
  width: 350px; /* 根据需要调整宽度 */
  margin-bottom: 20px;
}
.pdf-wrapper {
  max-height: 600px; /* 设置最大高度，你可以根据需要调整这个值 */
  overflow: auto; /* 如果内容超出高度，显示滚动条 */
  padding: 10px; /* 添加内边距 */
}
.button-container .el-button {
  font-size: 12px; /* 设置字体大小 */
  font-weight: bold;
  width: 120px; /* 设置按钮宽度 */
  height: 40px; /* 设置按钮高度 */
  /* 还可以添加其他样式，比如内边距、外边距等 */
  padding: 10px; /* 设置按钮内部文字与按钮边框的间距 */
  margin-right: 10px; /* 设置按钮之间的间距 */
}
.tableBar{
  display: flex;
  margin-bottom: 20px;
  align-items: center;
}
.button-container {
  margin-top: 20px; /* 设置按钮容器与上方组件之间的间距 */
  display: flex; /* 使按钮水平排列 */
  justify-content: flex-start; /* 按钮在主轴（水平方向）上对齐到起点 */
  margin-bottom: 15px;
}
.custom-table {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); /* 添加阴影效果 */
  background-color: rgb(229, 213, 213); /* 设置表格背景色为浅白色 */
  border: 1px solid #e9e9e9; /* 可选：添加边框以增强区分度 */
}
.custom-table .el-table__header-wrapper th {

}
.custom-checkbox {
  display: inline-flex;
  align-items: center;
  cursor: pointer;
  user-select: none;
  font-size: 16px;
  color: #333;
  transition: color 0.3s;
}

.custom-checkbox input[type="checkbox"] {
  display: none;
}

.custom-checkbox .checkmark {
  width: 24px;
  height: 24px;
  border: 2px solid #6871f1;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 10px;
  transition: background-color 0.3s, border-color 0.3s, transform 0.3s;
  transform-style: preserve-3d;
}

.custom-checkbox .checkmark::before {
  content: "\2713";
  font-size: 16px;
  color: transparent;
  transition: color 0.3s, transform 0.3s;
}

.custom-checkbox input[type="checkbox"]:checked + .checkmark {
  background-color: #6871f1;
  border-color: #6871f1;
  transform: scale(1.1) rotateZ(360deg) rotateY(360deg);
}

.custom-checkbox input[type="checkbox"]:checked + .checkmark::before {
  color: #fff;
}

.custom-checkbox:hover {
  color: #666;
}

.custom-checkbox:hover .checkmark {
  border-color: #666;
  background-color: #f0f0f0;
  transform: scale(1.05);
}

.custom-checkbox input[type="checkbox"]:focus + .checkmark {
  box-shadow: 0 0 3px 2px rgba(0, 0, 0, 0.2);
  outline: none;
}

.custom-checkbox .checkmark,
.custom-checkbox input[type="checkbox"]:checked + .checkmark {
  transition: background-color 1.3s, border-color 1.3s, color 1.3s, transform 0.3s;
}

/*!* 如果需要，您还可以为表格的其它部分添加样式，例如表头、单元格等 *!
.custom-table .el-table__header-wrapper th {
  background-color: rgba(255, 255, 255, 0.72); !* 设置表头背景色 *!
}
!* 根据需要添加自定义样式 *!
.custom-table .el-table__body tr:hover {
  background-color: #9d00fe; !* 设置鼠标悬停时的行背景色 *!
}*/
.loader {
  width: 48px;
  height: 48px;
  background: #353535;
  display: block;
  margin: 20px auto;
  position: relative;
  box-sizing: border-box;
  animation: rotationBack 1s ease-in-out infinite reverse;
  z-index: 9999
}

.loader::before {
  content: '';
  box-sizing: border-box;
  left: 0;
  top: 0;
  transform: rotate(45deg);
  position: absolute;
  width: 48px;
  height: 48px;
  background: #2e2e2e;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
}

.loader::after {
  content: '';
  box-sizing: border-box;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  background: rgb(0, 0, 0);
  transform: translate(-50%, -50%);
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
}

@keyframes rotationBack {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(-360deg);
  }
}
</style>